package uk.ac.ebi.bioinvindex.dao.ejb3;

import uk.ac.ebi.bioinvindex.dao.IdentifiableDAO;
import uk.ac.ebi.bioinvindex.model.impl.IdentifiableImpl;

import javax.persistence.EntityManager;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

/**
 * User: Nataliya Sklyar (nsklyar@ebi.ac.uk)
 * Date: Sep 4, 2007
 * <p/>
 * TODO: In general we should have DO and DomainObjectImpl, otherwise no
 * multiple mapping classes are possible.
 */
public class IdentifiableEJB3DAO<T extends IdentifiableImpl>
		extends AbstractEJB3DAO implements IdentifiableDAO<T> {

	protected Class<T> persistentClass;

	protected IdentifiableEJB3DAO() {
	}

	protected IdentifiableEJB3DAO(Class<T> persistentClass) {
		this.persistentClass = persistentClass;
	}

	public IdentifiableEJB3DAO(Class<T> persistentClass, EntityManager entityManager) {
		super(entityManager);
		this.persistentClass = persistentClass;
	}

	public Class<T> getPersistentClass() {
//		if (persistentClass == null) {
//			Type type1 = getClass()
//					.getGenericSuperclass();
//			Type type = ((ParameterizedType) type1).getActualTypeArguments()[0];
//			this.persistentClass = (Class<T>) type;
//		}
		return persistentClass;
	}

	@SuppressWarnings("unchecked")
	public T getById(Long id) {
		Class<T> clazz = getPersistentClass();
		return (T) getSession().get(clazz, id);
	}


	public List<T> getAll() {
		return getSession().createCriteria(getPersistentClass()).list();
	}

	public void update(T identifiable) {
		getSession().update(identifiable);
	}

	public Long save(T identifiable) {
		return (Long) getSession().save(identifiable);
	}

	/**
	 * @param id
	 * @return
	 */
	//ToDo: delete methods dont work properly for all classes. Problems with references
	public int deleteById(Long id) {
		T o = getById(id);
		if (o == null) {
			return 0;
		}
		delete(o);
		return 1;
	}

	public void delete(T identifiable) {
		getSession().delete(identifiable);
	}

}
